
"use client";

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { summarizeBlogPost } from '@/ai/flows/summarize-blog-post';
import { useToast } from '@/hooks/use-toast';
import { Loader2, Sparkles } from 'lucide-react';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';

export function PostContentClient({ content }: { content: string }) {
  const [summary, setSummary] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const { toast } = useToast();

  const handleSummarize = async () => {
    setIsLoading(true);
    setSummary('');
    try {
      const result = await summarizeBlogPost({ blogPostContent: content });
      if (result.summary) {
        setSummary(result.summary);
      } else {
        throw new Error("未能生成摘要。");
      }
    } catch (error) {
      console.error(error);
      toast({
        variant: 'destructive',
        title: '错误',
        description: '生成摘要时出错，请稍后再试。',
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <>
      <div className="my-8">
        <Button onClick={handleSummarize} disabled={isLoading}>
          {isLoading ? (
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          ) : (
            <Sparkles className="mr-2 h-4 w-4" />
          )}
          {isLoading ? '正在生成摘要...' : 'AI 生成摘要'}
        </Button>
      </div>

      {summary && (
        <Alert className="my-8 bg-accent/50">
          <Sparkles className="h-4 w-4" />
          <AlertTitle className="font-headline text-xl">文章摘要</AlertTitle>
          <AlertDescription className="mt-2 text-accent-foreground/80">
            {summary}
          </AlertDescription>
        </Alert>
      )}

      <div
        className="prose prose-lg max-w-none text-foreground prose-headings:font-headline prose-headings:text-primary-foreground prose-a:text-primary-foreground prose-strong:text-primary-foreground"
        dangerouslySetInnerHTML={{ __html: content.replace(/\n/g, '<br />') }}
      />
    </>
  );
}
